/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.andersen.web.controller;

import com.andersen.database.dao.EmployeeDao;
import com.andersen.database.entity.EmployeeEntity;
import com.andersen.database.entity.OfficeEntity;
import com.andersen.web.beans.EmplDataCommandForm;
import com.andersen.web.validating.EmplDataValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class EmployeeDataController extends AbstractController{

    @Autowired
    private EmployeeDao dao;

    @Autowired
    EmplDataValidator validator;

    @RequestMapping(value = "/emplData", method = RequestMethod.GET)
    public String ShowEmplData(@RequestParam(value = "id", required = true) String id, ModelMap model) {

        Long emplId = Long.parseLong(id);

        if (emplId > 0)
        {// редактирование

            model.addAttribute("title","Редактирование информации о сотруднике");
            model.addAttribute("action","Применить изменения");

            EmployeeEntity entity = dao.getEmployee(emplId);

            model.addAttribute("id",entity.getId());
            model.addAttribute("name",entity.getName());
            model.addAttribute("surname",entity.getSurname());
            model.addAttribute("patronymic",entity.getPatronymic());
            model.addAttribute("position",entity.getPosition());
            model.addAttribute("skype",entity.getSkype());
            model.addAttribute("phone",entity.getPhone());
            model.addAttribute("officeId",entity.getOfficeId());
            model.addAttribute("discharged",entity.isDischarged());


        }
        else
        { // добавление
            model.addAttribute("title","Добавление сотрудника");
            model.addAttribute("action","Добавить сотрудника");
            model.addAttribute("id",id);
        }


        model.addAttribute("emplDataCommandFormat", new EmplDataCommandForm());
        return "/templates/dialog_edit_employee";
    }


    @ModelAttribute(value = "officeNameList")
    public List<OfficeEntity> populateOfficeNameList() {
        return officeService.getOfficeList();
    }


    @RequestMapping( value = "/emplData", method= RequestMethod.POST)
    public String commitChanges(@ModelAttribute("emplDataCommandFormat") EmplDataCommandForm command,
                                BindingResult result, SessionStatus status, HttpServletResponse response, ModelMap map) {

        validator.validate(command, result);

        if (result.hasErrors()) { //ошибка валидации
            command.setValidationError(true);
            return "/templates/dialog_edit_employee";
        } else { //валидация прошла
            boolean dbRequestOk = false;
            LOG.info(command.toString());
            EmployeeEntity employee = EmployeeEntity.fromCommandForm(command);
            Long newId;
            if (command.getId()!=0){
                 dbRequestOk = employeeService.updateEmployee(employee);
            }
            else{
                dbRequestOk = employeeService.saveEmployee(employee) > ID_NOT_DEFINED;
            }

            if (!dbRequestOk) {
               LOG.info("FAIL");
            }
            status.setComplete();
            command.setValidationError(dbRequestOk);
            return "/templates/dialog_edit_employee";
        }
    }

}